// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  
  try {
    // 获取未支付订单数量
    const unpaidCount = await db.collection('orders').where({
      _openid: wxContext.OPENID,
      status: 'unpaid'
    }).count()
    
    // 获取待取餐订单数量
    const undeliveredCount = await db.collection('orders').where({
      _openid: wxContext.OPENID,
      status: 'undelivered'
    }).count()
    
    // 获取已完成订单数量
    const completedCount = await db.collection('orders').where({
      _openid: wxContext.OPENID,
      status: 'completed'
    }).count()
    
    return {
      success: true,
      data: {
        unpaid: unpaidCount.total,
        undelivered: undeliveredCount.total,
        completed: completedCount.total
      },
      openid: wxContext.OPENID
    }
  } catch (error) {
    return {
      success: false,
      message: '获取订单数量失败',
      error: error,
      openid: wxContext.OPENID
    }
  }
}